#include <stdio.h>
#include <unistd.h>
/* According to POSIX.1-2001 */
#include <sys/select.h>
/* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <poll.h>


#define ITERATIONS  (1000 * 100)

int checkfd_using_poll(int fd)
{
	struct pollfd pollfd = {fd, POLLIN, 0};
	int rv = 0;

	if (poll(&pollfd, 1, 0) > 1)
	{   
	    //POLLIN 有读事件发生； POLLHUP 是对端断开连接 
		rv = (pollfd.revents & (POLLIN | POLLHUP)) != 0;
	}

	return rv;
}

int checkfd_using_select(int fd)
{
	struct timeval timeout = {0,0};
	int rv = 0;
	fd_set set;
	FD_ZERO(&set);
	FD_SET(fd, &set);
	if (select(fd + 1, &set, NULL, NULL, &timeout) > 0)
	{
		rv = 1;
	}
	return rv;
}

int check_select_poll()
{
	unsigned int i;
	struct timeval start;
	struct timeval end;
	unsigned long millisecs_poll;
	unsigned long millisecs_select;

	gettimeofday(&start, NULL);

	for (i = 0 ; i < ITERATIONS ; ++i)
	{
		checkfd_using_poll(0);
	}
	gettimeofday(&end, NULL);

	millisecs_poll = ((end.tv_sec - start.tv_sec) * 1000 +
			(end.tv_usec - start.tv_usec) / 1000);

	gettimeofday(&start, NULL);

	for (i = 0 ; i < ITERATIONS ; ++i)
	{
		checkfd_using_select(0);
	}
	gettimeofday(&end, NULL);

	millisecs_select = ((end.tv_sec - start.tv_sec) * 1000 +
			(end.tv_usec - start.tv_usec) / 1000);

	if (millisecs_poll < millisecs_select) {
		return 1;
	} else {
		return 0;
	}
}

int main(int argc, char *argv[]){
    
    int ret = check_select_poll();
    if(ret){
        printf("poll() 的性能在该系统上更优秀！\n");
    }else{
        printf("select() 的性能在该系统上更优秀！\n");
    }
    return 0;
}
